# import_real_estate_data.py
import csv
from django.core.management.base import BaseCommand
from backend.models import CD  # 替换为你的应用名

class Command(BaseCommand):
    help = 'Import real estate data from a CSV file'

    def add_arguments(self, parser):
        parser.add_argument('csv_file', type=str, help='The path to the CSV file')

    def handle(self, *args, **kwargs):
        csv_file = kwargs['csv_file']

        with open(csv_file, mode='r', encoding='utf-8') as file:
            reader = csv.DictReader(file)
            for row in reader:
                # 创建 CD 对象
                cd = CD(
                    avg_transaction=float(row['avg_transaction']),
                    transaction_cycle=float(row['transaction_cycle']),
                    longitude=float(row['longitude']),
                    latitude=float(row['latitude']),
                    building_area=float(row['building_area']),
                    total_floors=int(row['total_floors']),
                    listing_price=float(row['listing_price']),
                    year_built=float(row['year_built']),
                    price_adjustment=float(row['price_adjustment']),
                    viewing_count=float(row['viewing_count']),
                    followers_count=float(row['followers_count']),
                    visitors_count=float(row['visitors_count']),
                    ladders=float(row['ladders']),
                    houses=float(row['houses']),
                    kitchens=float(row['kitchens']),
                    bedrooms=float(row['bedrooms']),
                    living_rooms=float(row['living_rooms']),
                    bathrooms=float(row['bathrooms']),
                    listing_year=float(row['listing_year']),
                    listing_month=float(row['listing_month']),
                    listing_day=float(row['listing_day']),
                    district_name=row['district_name'],
                    business_area=row['business_area'],
                    community_name=row['community_name'],
                    apartment_type=row['apartment_type'],
                    building_type=row['building_type'],
                    house_orientation=row['house_orientation'],
                    renovation_status=row['renovation_status'],
                    building_structure=row['building_structure'],
                    heating_method=row['heating_method'],
                    elevator_available=row['elevator_available'].lower() == 'true',  # 将字符串转换为布尔值
                    transaction_rights=row['transaction_rights'],
                    house_usage=row['house_usage'],
                    house_age=int(row['house_age']),
                    house_ownership=row['house_ownership']
                )
                # 保存对象到数据库
                cd.save()
                self.stdout.write(self.style.SUCCESS(f'Successfully added {row["community_name"]} - {row["listing_price"]}'))
